﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GKS.Extensions.IDictionary {
    /// <summary>
    /// A class that contains extensions to the IDictionary objects.
    /// </summary>
    public static class IDictionaryExtensions {
        /// <summary>
        /// A method that upserts (inserts or updates, depending on the case) the given value 
        /// of the specified key in this IDictionary object.
        /// </summary>
        /// <typeparam name="TKey">The type of the key of this IDictionary.</typeparam>
        /// <typeparam name="TValue">The type of the value of this IDictionary.</typeparam>
        /// <param name="dictionary">This IDictionary.</param>
        /// <param name="key">The key to upsert in this IDictionary.</param>
        /// <param name="value">The value to upsert in this IDictionary.</param>
        public static void Upsert<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, TValue value) {
            if (dictionary.ContainsKey(key)) {
                dictionary[key] = value;
            } else {
                dictionary.Add(key, value);
            }
        }

        /// <summary>
        /// A method that upserts (inserts or updates, depending on the case) the given KeyValuePair 
        /// in this IDictionary object.
        /// </summary>
        /// <typeparam name="TKey">The type of the key of this IDictionary.</typeparam>
        /// <typeparam name="TValue">The type of the value of this IDictionary.</typeparam>
        /// <param name="dictionary">This IDictionary.</param>
        /// <param name="kvPair">The KeyValuePair to upsert in this IDictionary.</param>
        public static void Upsert<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, KeyValuePair<TKey, TValue> kvPair) {
            dictionary.Upsert<TKey, TValue>(kvPair.Key, kvPair.Value);
        }
    }
}
